<?php 
/*!
 * Theme Name:One Nav
 * Theme URI:https://www.iotheme.cn/
 * Author:iowen
 * Author URI:https://www.iowen.cn/
 */
if ( ! defined( 'ABSPATH' ) ) { exit; }

if(!session_id()) @session_start();

require_once get_theme_file_path('/inc/classes/open.qq.class.php');
require_once get_theme_file_path('/inc/classes/open.sina.class.php');
require_once get_theme_file_path('/inc/classes/open.wechat.class.php');

//检测IO_ID是否重复
function userioid_exists( $ioid ) {
    global $wpdb;
    $user = $wpdb->get_row(
        $wpdb->prepare(
            "SELECT * FROM $wpdb->users WHERE io_id = %s LIMIT 1",
            $ioid
        )
    );
    if ( ! $user ) {
        return false;
    }else{
        return $user->ID;
    }
} 
//添加 io_id
add_action('user_register', 'io_register_extra_fields');
function io_register_extra_fields($user_id) {
	global $wpdb;

    $prename = 'io';
    $extname = rand(100000,999998);
    $ioid = $prename.$extname;
    if(userioid_exists($ioid)){
        while(userioid_exists($ioid)){ $extname++; }
        $ioid = $prename.$extname;
    }
    $wpdb->query("UPDATE $wpdb->users SET io_id = '$ioid' WHERE ID = '$user_id'"); 
} 
function openloginFormButton(){
    echo '<p id="openlogin-box" class="openlogin-box">'; 
    if(io_get_option('open_qq')) echo '<a href="'.get_theme_file_uri('/inc/auth/qq.php').'?loginurl='.io_get_option('open_login_url').'" title="QQ快速登录" rel="nofollow" class="openlogin-qq-a"><i class="iconfont icon-qq"></i></a>';
    if(io_get_option('open_weibo')) echo '<a href="'.get_theme_file_uri('/inc/auth/sina.php').'?loginurl='.io_get_option('open_login_url').'" title="微博快速登录" rel="nofollow" class="openlogin-weibo-a"><i class="iconfont icon-weibo"></i></a>';
    if(io_get_option('open_wechat')) echo '<a href="'.get_theme_file_uri('/inc/auth/wechat.php').'" title="微信快速登录" rel="nofollow" class="openlogin-wechat-a"><i class="iconfont icon-wechat"></i></a>';
    echo '</p>';
?>
<?php
}
add_filter('login_form', 'openloginFormButton');

/**
 * 判断用户是否已经绑定了开放平台账户.
 *
 * @param string $type
 * @param int    $user_id
 *
 * @return bool
 */
function io_has_connect($type = 'qq', $user_id = 0)
{
    $user_id = $user_id ?: get_current_user_id();
    switch ($type) {
        case 'qq':
            return get_user_meta($user_id, 'qq_openid', true); 
        case 'sina':
            return get_user_meta($user_id, 'sina_openid', true); 
        case 'wechat':
            return get_user_meta($user_id, 'wechat_openid', true); 
        default :
            return false;
    }

    return false;
} 
